<template>
  <div>
    <!-- 返回 -->
    <top-back>
      <template v-slot:back>修改收件地址</template>
    </top-back>

    <!-- 编辑 -->
    <form @submit.prevent>
      <van-cell-group class="common">
        <van-field v-model="info.name" label="收件人" />
        <van-field v-model="info.tel" label="联系方式" />

        <van-field v-model="address" label="地区" @click="isShow = !isShow" />
        <van-action-sheet v-model="isShow">
          <van-area
            title="地区"
            :area-list="areaList"
            :columns-num="3"
            @cancel="isShow = !isShow"
            @confirm="onUpdate"
          />
        </van-action-sheet>

        <van-field v-model="detail" label="详细地址" />
      </van-cell-group>

      <van-cell title="设置为默认地址" class="common">
        <template #right-icon>
          <van-switch v-model="ischecked" size="24" />
        </template>
      </van-cell>

      <van-button block class="common update btn" @click="onSave"
        >保存</van-button
      >
      <van-button block class="common btn" @click="onDel">删除</van-button>
    </form>
  </div>
</template>

<script>
import { Toast, Dialog } from 'vant'
import { areaList } from '@vant/area-data'
import TopBack from '@/components/Mine/TopBack'

export default {
  name: 'SetAddress',
  components: { TopBack },
  data () {
    return {
      areaList,
      searchResult: [],
      isShow: false,
      ischecked: false,
      info: {},
      address: '',
      detail: '',
      newInfo: {}
    }
  },
  created () {
    const id = this.$route.params.id
    this.info = this.$store.getters.address.find(item => item.id === Number(id))
    this.address = this.info.address.split(' ')[0]
    this.detail = this.info.address.split(' ')[1]
  },
  methods: {
    onSave () {
      this.info.address = this.address + ' ' + this.detail
      this.info.isDefault = this.ischecked
      for (const k in this.info) {
        this.newInfo[k] = this.info[k]
      }
      this.$store.dispatch('setAddress', this.newInfo)
      Toast('修改成功')
      this.$router.go(-1)
    },
    onDel () {
      Dialog.confirm({
        message: '确认删除吗？'
      }).then(() => {
        this.$store.dispatch('delAddress', this.info.id)
        Toast('删除成功')
        this.$router.go(-1)
      })
    },
    onClickLeft () {
      this.$router.go(-1)
    },
    onClickRight () {
      Toast('按钮')
    },
    onUpdate (val) {
      this.address = val.reduce((s, item) => s + item.name, '')
      this.isShow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.common {
  width: 7.1rem;
  margin: 0 auto;
  border-radius: 10px;
}
.van-cell-group {
  margin: 10px;
}
.update {
  margin: 50px auto 10px;
  background-color: #ee0a24;
  color: #fff;
}
.btn {
  border-radius: 30px;
}
</style>
